<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

	private $appid = 'wx893194fd29941685';
	private $appsecret = '677ec003845d567a748c5659231a3cc5';

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->helper('cookie');
    }

	public function index()
	{
		$openid = $this->input->cookie('openid');
		if ($openid) {
			$user = $this->db->get_where('member', array('openid'=>$openid))->row_array();

			if (empty($user)) {
				$user['openid'] = $openid;
				$user['username'] =NULL;
				$user['sex'] =NULL;
				$user['phone'] = NULL;
				$user['province'] = 0;
				$user['city'] = 0;
				$user['company'] = NULL;
				$user['post'] = NULL;
				$user['hobby'] =  NULL;
				$user['declaration'] =  NULL;
				$user['headimgurl'] =  NULL;
			}
			
			$this->load->view('index',array('user'=>$user));
		}else{
			redirect('welcome/to_oauth/index');
		}
	}




	//保存用户信息
	public function save_userinfo(){

		$openid = $this->input->cookie('openid');
		// var_dump($openid) ;exit;
		if (!$openid) {
			exit(json_encode(array('status'=>'openid')));
		}

		$username    = $this->input->post('username');
		$sex         = $this->input->post('sex');
		$phone       = $this->input->post('phone');
		$province    = $this->input->post('province');
		$city        = $this->input->post('city');
		$company     = $this->input->post('company');
		$post        = $this->input->post('post');
		$hobby       = $this->input->post('hobby');
		$declaration = $this->input->post('declaration');
		$headimgurl  = $this->input->post('headimgurl');



		if (strlen(trim($username))===0 || strlen(trim($username))>20) {
			exit(json_encode(array('status'=>'username')));
		}

		if (strlen(trim($sex))===0 || strlen(trim($sex))>10) {
			exit(json_encode(array('status'=>'sex')));
		}

		if (strlen(trim($phone))===0 || strlen(trim($phone))>11) {
			exit(json_encode(array('status'=>'phone')));
		}

		if (strlen(trim($province))===0 || strlen(trim($province))>20) {
			exit(json_encode(array('status'=>'province')));
		}

		if (strlen(trim($city))===0 || strlen(trim($city))>20) {
			exit(json_encode(array('status'=>'city')));
		}

		if (strlen(trim($company))===0 || strlen(trim($company))>200) {
			exit(json_encode(array('status'=>'company')));
		}

		if (strlen(trim($post))===0 || strlen(trim($post))>200) {
			exit(json_encode(array('status'=>'post')));
		}

		if (strlen(trim($hobby))===0 || strlen(trim($hobby))>200) {
			exit(json_encode(array('status'=>'hobby')));
		}

		if (strlen(trim($declaration))===0 || strlen(trim($declaration))>200) {
			exit(json_encode(array('status'=>'declaration')));
		}

		if (strlen(trim($headimgurl))>200) {
			exit(json_encode(array('status'=>'headimgurl')));
		}


		$user = $this->db->get_where('member',array('openid'=>$openid))->row_array();
		if (!empty($user)) {
			$data = $this->input->post(NULL,true);

			$this->db->where('openid', $openid);

			if ($this->db->update('member', $data)) {
				echo json_encode(array('status'=>'success'));
			}else{
				echo json_encode(array('status'=>'fail'));
			}

		}else{

			$data = $this->input->post(NULL,true);
			$data['openid'] = $openid;
			if ($this->db->insert('member', $data)) {
				echo json_encode(array('status'=>'success'));
			}else{
				echo json_encode(array('status'=>'fail'));
			}
		}




	}


	//查找某一用户信息
	public function getMember($id = 0){

		$user = $this->db->select('username,province,hobby,declaration,headimgurl')->get_where('member', array('id'=>(int)$id))->row_array();
		if (empty($user)) {
			echo json_encode(array('code' => '-1','message'=>'没有找到此用户','data'=>''));
		}else{
			$province = $this->db->select('name')->get_where('area',array('id'=>$user['province']))->row_array();
			$user['province'] = $province['name'];
			echo json_encode(array('code' => '0','message'=>'成功','data'=>$user));
		}
	}



	//上传图片
	public function upload(){
		$img  = $this->input->post('img');

		// echo $img;exit;
		$img  = str_replace('data:image/png;base64,', '', $img);
		$img  = str_replace(' ', '+', $img);
		$data = base64_decode($img);

        $save_file = 'uploads/'.uniqid().'.png';
        $result = file_put_contents('./'.$save_file, $data);

        echo json_encode(array('status'=>'success','imagePath'=>$save_file));
    }


    public function province(){
    	$pro = $this->db->order_by('sort')->get_where('area',array('parent_id'=>0))->result_array();
    	echo json_encode($pro);
    }

    public function city($id=2600){
    	$id = ((int)$id==0)?2600:(int)$id;
    	$city = $this->db->get_where('area',array('parent_id'=>(int)$id))->result_array();
    	if (empty($city)) {
    		$city = $this->db->get_where('area',array('id'=>(int)$id))->result_array();
    	}
    	echo json_encode($city);
    }


    public function to_oauth($state=''){

    	$redirect_url = urlencode(site_url('welcome/get_code'));
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
		header("Location:".$url);
    }

    public function get_code(){

		$code = $this->input->get('code');
		$state = $this->input->get('state');

		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";

		$result = (array)json_decode(file_get_contents($url));

		if (isset($result['openid'])) {

			$this->input->set_cookie('openid', $result['openid'], 60*60*24*30*5);

			$openid       =  $result['openid'];
			$access_token =  $result['access_token'];
			$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
			$wechat_user = (array)json_decode(file_get_contents($url));
			unset($wechat_user['privilege']);
			unset($wechat_user['unionid']);

			$user = $this->db->get_where('wechat_user', array('openid'=>$openid))->row_array();
			if (empty($user)) {
				$this->db->insert('wechat_user', $wechat_user);
				// $this->db->insert('member', array('openid'=>$openid));

			}else{
				$this->db->where('openid', $openid);
				$this->db->update('wechat_user', $wechat_user);
			}

			//签到
			if ($state=='signUp') {
				$sign = $this->db->get_where('sign_up_user', array('openid'=>$openid))->row_array();
				if (empty($sign)) {
					$this->db->insert('sign_up_user', $wechat_user);
				}else{
					$this->db->where('openid', $openid);
					$this->db->update('sign_up_user', $wechat_user);
				}
			}

			$this->_my_redirect($state);
		}
	}


	public function delete_cookie(){
		var_dump(delete_cookie('openid'));
	}

	public function set_cookie(){
		$this->input->set_cookie('openid', 'oprQ4t5D-n3pTs5N--CutAXFuOEE', 60*60*24*30*5);
	}

	private function _my_redirect($uri=''){
		if ($uri=='quiz') {
			header('Location:'.base_url().'public/quiz.html');
			exit;
		}else if($uri=='vote'){
			redirect("welcome/vote");
		}else if($uri=='signUp'){
			redirect("welcome/sign_up_success");
		}elseif(is_numeric($uri) ){
			
			header('Location:'.base_url().'public/players.html?id='.$uri);
		}else{
			redirect("welcome/{$url}");
		}
	}


	public function quiz(){
		$quiz = $this->db->select('username,phone')->get_where('quiz',array('openid'=>$this->input->cookie('openid')))->row_array();
		echo json_encode($quiz);
	}

	public function save_quiz(){
		$openid   = $this->input->cookie('openid');
		$username = $this->input->post('username');
		$phone    = $this->input->post('phone');


		if (strlen(trim($openid))===0 || strlen(trim($openid))>200) {
			exit(json_encode(array('status'=>'openid')));
		}


		if (strlen(trim($username))===0 || strlen(trim($username))>20) {
			exit(json_encode(array('status'=>'username')));
		}


		if (strlen(trim($phone))===0 || strlen(trim($phone))>11) {
			exit(json_encode(array('status'=>'phone')));
		}

		$wechat_user = $this->db->get_where('wechat_user',array('openid'=>$openid))->row_array();
		if (empty($wechat_user)) {
			exit(json_encode(array('status'=>'wechat_user_no')));
		}

		$data['username'] = $username;
		$data['phone']    = $phone;
		$data['headimgurl'] = $wechat_user['headimgurl'];


		$quiz = $this->db->get_where('quiz',array('openid'=>$openid))->result_array();
		if (!empty($quiz)) {
			$this->db->where('openid', $openid);
			($this->db->update('quiz', $data))?exit(json_encode(array('status'=>'update_ok'))):exit(json_encode(array('status'=>'update_fail')));
		}

		$data['openid']   = $openid;
		($this->db->insert('quiz', $data)) ?exit(json_encode(array('status'=>'ok'))):exit(json_encode(array('status'=>'fail')));

	}


	public function sign_up(){
		//todo 用户签到
		redirect('welcome/to_oauth/signUp');
		echo 'sign up.';
	}

	public function sign_up_success(){
		header("Location:http://forestry.xuanzhen-tech.com/public/checkin.html");
	}




	public function vote(){

		$openid = $this->input->cookie('openid');
		if (!$openid) {
			redirect('welcome/to_oauth/vote');
		}

		$arr = $this->db->get_where('member',array('is_vote'=>1))->result_array();
		if (empty($arr)) {
			exit('no data.');
		}

		$this->load->view('vote',array('data'=>$arr));
	}

	public function vote_count($id=0){

		//未授权 要先授权
		$openid = $this->input->cookie('openid');
		if (!$openid) {
			exit(json_encode(array('code' =>-1 ,'message'=>'您还没有授权.','data'=>'' )));
		}

		//检查被投票用户是否存在
		$member = $this->db->get_where('member',array('id'=>$id))->row_array();
		if (empty($member)) {
			exit(json_encode(array('code' =>-2 ,'message'=>'无此用户' )));
		}

		//检查投票用户是否存在
		$wechat_user = $this->db->get_where('wechat_user',array('openid'=>$openid))->row_array();
		if (empty($wechat_user)) {
			exit(json_encode(array('code' =>-3 ,'message'=>'无效Openid' )));
		}

		//不能给自己投票
		if ($member['openid']===$wechat_user['openid']) {
			exit(json_encode(array('code' =>-4 ,'message'=>'您不能给自己投票' )));
		}

		//检查是否投过票
		$vote = $this->db->get_where('vote',array('openid'=>$openid,'create_time'=>date('Y-m-d',time() )  ))->row_array();

		if (!empty($vote)) {
			exit(json_encode(array('code' =>-5 ,'message'=>'您今天已经投过票了！' )));
		}
		$this->db->trans_start();
		//插入投票记录
		$data = array('openid' =>$openid , 'create_time'=>date('Y-m-d',time()) ,'member_id'=>(int)$id );
		$this->db->insert('vote', $data);
		//修改用户票数
		$sql = 'UPDATE member SET vote_count=vote_count+1 WHERE id=?';
		if ($this->db->query($sql,array('id'=>(int)$id))) {
			$this->db->trans_complete();
			exit(json_encode(array('code' =>0 ,'message'=>'投票成功','data'=>'' )));
		}else{
			$this->db->trans_complete();
			exit(json_encode(array('code' =>-6 ,'message'=>'投票失败','data'=>'' )));
		}
	}


	public function ranking(){

		$sql = 'SELECT SUM(vote_count) as `vote_count` FROM member';
		$vote_count = $this->db->query($sql)->row_array();
		$vote_total_count = $vote_count['vote_count'];

		$arr = $this->db->order_by('vote_count','desc')->get_where('member',array('is_vote'=>1))->result_array();


		$this->load->view('ranking',array('data'=>$arr,'vote_total_count'=>$vote_total_count));
	}

	public function rankingpc(){
		$sql = 'SELECT username,headimgurl,vote_count FROM `member` ORDER BY vote_count DESC LIMIT 6';
		$arr['list'] = $this->db->query($sql)->result_array();

		// $sql = 'SELECT SUM(vote_count) total FROM (SELECT username,headimgurl,vote_count FROM `member` ORDER BY vote_count DESC LIMIT 6) m';
		$sql = 'SELECT SUM(vote_count) total FROM member';
		$arr['total'] = $this->db->query($sql)->row_array();		
		echo json_encode($arr);
	}



}
